package arch.dao.impl.user;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import arch.dao.user.UserDeptDao;
import arch.domain.user.Dept;
import arch.domain.user.User;
import arch.domain.user.relation.UserDept;
/**
 * 
 * @author ZhaoWangLong Sep 7, 2012
 *
 */
@Repository("userDeptDao")
public class UserDeptImpl implements UserDeptDao {
	@Resource private JdbcTemplate jdbcTemplate;
	private final Logger logger = Logger.getLogger(UserDeptImpl.class);
	
	public Integer query(String sql, Object... objects) {
		return this.jdbcTemplate.queryForInt(sql,objects);
	}
	@SuppressWarnings("unchecked")
	public List<UserDept> queryList(String sql, Object... objects) {
		logger.debug("SQL > "+sql);
		return this.jdbcTemplate.query(sql, objects, new RowMapper(){

			public Object mapRow(ResultSet rs, int i) throws SQLException {
				UserDept userDept = new UserDept();
				
				User user = new User();
				user.setUserId(rs.getString("USER_ID"));
				userDept.setUser(user);
				
				Dept dept = new Dept();
				dept.setDeptId(rs.getString("DEPT_ID"));
				userDept.setDept(dept);

				userDept.setIndex(rs.getInt("INDEX"));
				return userDept;
			}});
	}
	
	public void remove(UserDept userDept) {
		String sql = "delete from ID_DEPT_USER where (DEPT_ID, USER_ID) = (?,?)";
		
		this.jdbcTemplate.update(sql,new Object[]{
				userDept.getDept().getDeptId(),
				userDept.getUser().getUserId()
		});
	}
	public void merge(UserDept userDept) {
		String sql = "update ID_DEPT_USER set INDEX = ? where (DEPT_ID, USER_ID) = (?,?)";
		
		this.jdbcTemplate.update(sql,new Object[]{
				userDept.getIndex(),
				userDept.getDept().getDeptId(),
				userDept.getUser().getUserId()
		});
	}
	public void persist(UserDept userDept) {
		String sql = " insert into ID_DEPT_USER (DEPT_ID, USER_ID,INDEX) values (?,?,?)";

		this.jdbcTemplate.update(sql,new Object[]{
				userDept.getDept().getDeptId(),
				userDept.getUser().getUserId(),
				userDept.getIndex()
		});
	}
	public void persist(List<UserDept> userDepts) {
		String sql = " insert into ID_DEPT_USER (DEPT_ID, USER_ID,INDEX) values (?,?,?)";
		this.jdbcTemplate.batchUpdate(sql, new UserDeptBatchInsertSetter(userDepts));
	}
	public void remove(List<UserDept> userDepts) {
		String sql = "delete from ID_DEPT_USER where (DEPT_ID, USER_ID) = (?,?)";
		this.jdbcTemplate.batchUpdate(sql, new UserDeptBatchDeleteSetter(userDepts));
	}
	public void remove(String sql, Object... objects) {
		this.jdbcTemplate.update(sql,objects);
	}
}
